/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.increase.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.increase.domain.Increase;
import com.jeeplus.increase.service.IncreaseService;
import com.jeeplus.increase.service.dto.IncreaseDTO;
import com.jeeplus.increase.service.dto.MemberTrendDTO;
import com.jeeplus.increase.service.mapstruct.IncreaseWrapper;
import com.jeeplus.sys.domain.Post;
import com.jeeplus.sys.service.PostService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 人数增长趋势Controller
 * @author 淋漓
 * @version 2024-05-30
 */

@Api(tags ="人数增长趋势")
@RestController
@RequestMapping(value = "/increase/trend")
public class MemberIncreaseController {

	@Autowired
	private IncreaseService increaseService;

	@Autowired
	private IncreaseWrapper increaseWrapper;

	@Autowired
	private PostService postService;

	/**
	 * 数据列表数据
	 */
	@ApiLog("查询数据列表数据")
	@ApiOperation(value = "查询数据列表数据")
	@PreAuthorize("hasAuthority('increase:trend:member')")
	@GetMapping("member")
	public ResponseEntity<MemberTrendDTO> selectTrend(@RequestParam("postId") String postId){
		QueryWrapper<Increase> increaseQueryWrapper = new QueryWrapper<Increase>().eq("post_id", postId);
		Increase increase = increaseService.getOne(increaseQueryWrapper);
		MemberTrendDTO memberTrendDTO = BeanUtil.copyProperties(increase, MemberTrendDTO.class);
		memberTrendDTO.initWeekList();
		return ResponseEntity.ok (memberTrendDTO);
	}

	/**
	 * 保存数据
	 */
	@ApiLog("保存数据")
	@ApiOperation(value = "保存数据")
	@PreAuthorize("hasAnyAuthority('increase:trend:save')")
	@PostMapping("save")
	public  ResponseEntity <String> saveOrUpdate(@Valid @RequestBody IncreaseDTO increaseDTO) {
		if(increaseDTO.getPostId()==null){
			increaseDTO.setPostId(postService.getOne(new QueryWrapper<Post>().eq("name", increaseDTO.getPostName()).eq("del_flag","0")).getId());
		}
		//新增或编辑表单保存
		Increase increase = increaseService.getOne(new QueryWrapper<Increase>().eq("post_id", increaseDTO.getPostId()));
		if(increase == null){
			increaseService.saveOrUpdate (increaseWrapper.toEntity (increaseDTO));
		}
		else {
			increaseDTO.setId(increase.getId());
			increaseService.updateById(BeanUtil.copyProperties(increaseDTO,Increase.class));
		}
		return ResponseEntity.ok ( "保存数据成功" );
	}


	/**
	 * 数据列表数据
	 */
	@ApiLog("查询数据列表数据")
	@ApiOperation(value = "查询数据列表数据")
	@PreAuthorize("hasAuthority('increase:increase:list')")
	@GetMapping("list")
	public ResponseEntity<IPage<IncreaseDTO>> list(IncreaseDTO increaseDTO, Page<Increase> page) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (increaseDTO, IncreaseDTO.class);
		IPage<IncreaseDTO> result = increaseWrapper.toDTO ( increaseService.page (page, queryWrapper) );
		return ResponseEntity.ok (result);
	}


	/**
	 * 根据Id获取数据数据
	 */
	@ApiLog("根据Id获取数据数据")
	@ApiOperation(value = "根据Id获取数据数据")
	@PreAuthorize("hasAnyAuthority('increase:increase:view','increase:increase:add','increase:increase:edit')")
	@GetMapping("queryById")
	public ResponseEntity<IncreaseDTO> queryById(String id) {
		return ResponseEntity.ok ( increaseWrapper.toDTO ( increaseService.getById ( id ) ) );
	}


	/**
	 * 删除数据
	 */
	@ApiLog("删除数据")
	@ApiOperation(value = "删除数据")
	@PreAuthorize("hasAuthority('increase:increase:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        increaseService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除数据成功" );
	}
	
    /**
     * 导出数据数据
     *
     * @param increaseDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出数据数据")
    @PreAuthorize("hasAnyAuthority('increase:increase:export')")
    @GetMapping("export")
    public void exportFile(IncreaseDTO increaseDTO, Page <Increase> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (increaseDTO, IncreaseDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据
            
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List < Increase> result = increaseService.page ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( increaseService, increaseWrapper ).exportExcel ( result,  options.getSheetName ( ), IncreaseDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入数据数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('increase:increase:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( increaseService, increaseWrapper ).importExcel ( file, IncreaseDTO.class );
        return ResponseEntity.ok ( result );
    }

    /**
     * 下载导入数据数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('increase:increase:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "数据数据导入模板.xlsx";
        List<IncreaseDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( increaseService, increaseWrapper ).exportExcel ( list,  "数据数据", IncreaseDTO.class, fileName, null, response );
    }


}
